<template>
  <div class="h-[100vh] overflow-hidden">
    <!-- 头部 -->
    <header class="w-full h-[72px] bg-[var(--headBg)] px-2 flex items-center justify-between">
      <div class="flex flex-1 items-center h-full">
        <i class="iconfont icon-qiepian rounded-full bg-[var(--text)] text-[var(--contentBg)] py-1 px-2 mx-1"></i>
        <span class="ml-2 text-lg text-[var(--text)]">梦音阁音乐</span>
        <span @click="$router.back()"
          class="iconfont icon-a-zuojiantouzhixiangzuojiantou cursor-pointer rounded-full hover:bg-[var(--hoverBg)] text-[var(--text)] transition-all py-2 px-3 mx-1 ml-24"></span>
        <span @click="$router.go(1)"
          class="iconfont icon-a-youjiantouzhixiangyoujiantou cursor-pointer rounded-full hover:bg-[var(--hoverBg)] text-[var(--text)] transition-all py-2 px-3 ml-1 mr-4"></span>
        <!-- 音乐搜索 -->
        <musicSearch></musicSearch>
        <span
          class="iconfont icon-maikefeng cursor-pointer rounded-full hover:bg-[var(--hoverBg)] text-[var(--text)] transition-all py-2 px-3 mx-1">
        </span>
      </div>
      <div class="flex flex-1 items-center h-full justify-end">
        <!-- 未登录 -->
        <login v-if="isLogin"></login>
        <!-- 已登录 -->
        <user v-else></user>
        <div class="relative">
          <span
            class="bg-[var(--hoverBg)] cursor-pointer text-[var(--contentBg)] px-1 text-xs rounded-full ml-2 mr-4 select-none">vip开通
            &gt;</span>
          <i class="header_icon iconfont icon-tiaoseban" @click="themeValue = !themeValue"></i>
          <i class="header_icon iconfont icon-shezhi"></i>
          <i class="header_icon iconfont icon-youjian_o"></i>
          <i class="header_icon iconfont icon-qiepian"></i>
          <i class="header_icon iconfont icon-chuangkou"></i>
          <i class="header_icon iconfont icon-zuixiaohua" @click="minBtn"></i>
          <i class="header_icon iconfont icon-a-8Jxiangxiahuanyuan" @click="maxBtn"></i>
          <i class="header_icon iconfont icon-guanbi" @click="closeBtn"></i>
          <!-- 调色板 -->
          <Transition name="fade">
            <theme v-if="themeValue" />
          </Transition>

        </div>
      </div>
    </header>
    <!-- 主体 -->
    <main class=" bg-[var(--headBg)] flex h-[calc(100vh-178px)] overflow-hidden">
      <!-- 左侧边栏 -->
      <div class="min-w-fit h-[calc(100vh-179px)] overflow-auto no-scrollbar">
        <ul @click="handleClick">
          <li @click="goToHome"
            class="leftMenu w-52 transition-all h-11 rounded-r-3xl text-[var(--text)] mb-1 pl-4 hover:cursor-pointer flex justify-start items-center active">
            <i class="mr-2 iconfont icon-shouye before:text-xl"></i>
            <span>发现音乐</span>
          </li>
          <li @click="goToBolg" class="listStyle leftMenu">
            <i class="mr-2 iconfont icon-area before:text-xl"></i>
            <span>博客</span>
          </li>
          <li class="leftMenu listStyle">
            <i class="mr-2 iconfont icon-shipinbofang before:text-xl"></i>
            <span>视频</span>
          </li>
          <li class="leftMenu listStyle">
            <i class="mr-2 iconfont icon-yonghu-yuan before:text-xl"></i>
            <span>关注</span>
          </li>
          <li class="leftMenu listStyle">
            <i class="mr-2 iconfont icon-zhibo before:text-xl"></i>
            <span>直播</span>
          </li>
          <li class="leftMenu listStyle">
            <i class="mr-2 iconfont icon-shouyinji before:text-xl"></i>
            <span>私人漫游</span>
          </li>
        </ul>
        <p class="text-slate-400 text-xs pl-3 pb-2">我的音乐</p>
        <ul>
          <li class="leftMenu listStyle">
            <i class="mr-2 iconfont icon-aixin before:text-xl"></i>
            <span>我喜欢的音乐</span>
            <span
              class="iconfont icon-line_aixin px-3 border border-[var(--icon)] before:text-2xl transition-all hover:border-transparent ml-2 hover:bg-[var(--playBg)] hover:text-[var(--contentBg)] rounded-2xl"></span>
          </li>
          <li class="leftMenu listStyle">
            <i class="mr-2 iconfont icon-xiazai before:text-xl"></i>
            <span>本地与下载</span>
          </li>
          <li class="leftMenu listStyle">
            <i class="mr-2 iconfont icon-round-restore-px before:text-xl"></i>
            <span>最近播放</span>
          </li>
        </ul>
        <div>
          <p v-if="userSongList_playlist.length" class="text-[var(--iconBg)] text-xs pl-3 pb-2 hover:cursor-pointer">
            创建的歌单 ({{ userSongList_playlist.length }})<span @click="showUserSongList = !showUserSongList"
              class="text-[10px] text-[--iconBg] ml-1 inline-block w-5 text-center transition-all"
              :class="{ 'rotate-180': showUserSongList }">&#9660</span><span
              class="text-2xl font-light align-sub ml-[90px]">+</span></p>
          <ul v-show="showUserSongList">
            <li class="listStyle" v-for="item in userSongList_playlist" :key="item.id"
              @click="goToSongListDetail(item.id)">
              <img class="object-cover w-10 h-10 rounded-md" :src="item.coverImgUrl">
              <span class="line-clamp-1 text-sm px-2">{{ item.name }}</span>
            </li>
          </ul>
        </div>
      </div>
      <!-- 中间内容区域 -->
      <div id="main"
        class="px-12 py-7 bg-[var(--contentBg)] z-0 relative w-full rounded-tl-2xl h-[calc(100vh-179px)] overflow-auto no-scrollbar flex justify-center">
        <router-view></router-view>
      </div>
    </main>
    <!-- 播放器 -->
    <playback class="relative" ref="playbackRef" @getPlayTime="getPlayTime" @lrcInfo="lrcInfo"
      @openDetails="openDetails" @ChangeRotatePause="ChangeRotatePause" @ChangeRotateRun="ChangeRotateRun"
      @getMusicInfo="getMusicInfo">
    </playback>
    <!-- 歌词详情页 -->
    <div ref="lrcRef" class="transition-all translate-y-0 duration-700 w-full h-full  bg-no-repeat z-50 animate_bg">
      <!-- 蒙版 -->
      <div class="w-full h-full bg-[rgba(0,0,0,.3)] backdrop-blur-3xl  -z-50 absolute">
      </div>
      <!-- 顶部导航栏 -->
      <div v-if="isFullScreen" class="w-full h-16 flex justify-between items-center px-10">
        <div class="flex items-center gap-2">
          <div class="p-2 flex items-center justify-center rounded bg-[rgba(0,0,0,0.3)] hover:cursor-pointer"
            @click="backToHome">
            <el-icon color="#fff">
              <ArrowDownBold />
            </el-icon>
          </div>
          <div class="p-2 flex items-center justify-center rounded bg-[rgba(0,0,0,0.3)] hover:cursor-pointer"
            @click="fullScreen">
            <svg t="1715238280651" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg"
              p-id="3497" width="15" height="16">
              <path
                d="M128 384h85.33V213.33H384V128H128zM640 128v85.33h170.67V384H896V128zM810.67 810.67H640V896h256V640h-85.33zM213.33 640H128v256h256v-85.33H213.33z"
                p-id="3498" fill="#ffffff"></path>
            </svg>
          </div>
        </div>
        <div class="flex items-center">
          <div class="text-[var(--icon)] flex items-center text-sm px-2 py-1 rounded-full bg-[rgba(0,0,0,0.2)]">
            <el-icon color="#fff" :size="10">
              <ArrowDownBold />
            </el-icon>
            <span class="ml-1 hover:cursor-pointer">默认模式</span>
          </div>
          <i class="header_icon iconfont icon-zuixiaohua text-[var(--icon)] ml-2 px-3" @click="minBtn"></i>
          <i class="header_icon iconfont icon-a-8Jxiangxiahuanyuan text-[var(--icon)] mx-2 px-3" @click="maxBtn"></i>
          <i class="header_icon iconfont icon-guanbi text-[var(--icon)] px-3" @click="closeBtn"></i>
        </div>
      </div>
      <!-- 退出全屏按钮 -->
      <div v-else class="w-full h-16 flex justify-between items-center px-10">
        <div class="p-2 flex items-center justify-center rounded bg-[rgba(0,0,0,0.3)] hover:cursor-pointer"
          @click="backFullScreen">
          <svg t="1715239643576" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg"
            p-id="3406" width="16" height="15">
            <path
              d="M142.4 96.8l-44.8 44.8 173.6 174.4-68 68H384V203.2l-67.2 67.2zM752.8 316l173.6-174.4-44.8-44.8-174.4 173.6-67.2-67.2V384h180.8zM270.4 707.2l-169.6 170.4 44.8 49.6 170.4-174.4 68 68V640H203.2zM820.8 640H640v180.8l68-68 170.4 174.4 44.8-49.6-169.6-170.4z"
              p-id="3407" fill="#ffffff"></path>
          </svg>
        </div>
      </div>
      <!-- 歌词内容区域 -->
      <div class="grid grid-cols-2 h-[calc(100vh-170px)] px-10">
        <div class=" flex flex-col justify-center items-center">
          <div class="relative">
            <!-- 唱针图片 -->
            <img ref="stylusImgRef" src="../../assets/image/R-C.png" alt=""
              class="object-cover w-72 absolute right-0 top-0 translate-y-[-70%] z-50 duration-300"
              :class="isPlay ? '-rotate-[100deg]' : '-rotate-[72deg]'">
            <!-- 旋转区域 -->
            <div ref="rotateContentRef" class="animate-spin -z-50">
              <div class="object-cover w-80 h-80 border-8 border-gray-400 bg-black backdrop-blur-sm rounded-full">
              </div>
              <img crossorigin="anonymous" :src="vocalInfo?.al.picUrl" alt=""
                class="rounded-full border-8 border-gray-900 object-cover w-56 h-5w-56 absolute top-1/2 left-1/2 translate-x-[-50%] translate-y-[-50%]">
            </div>
          </div>
        </div>
        <div>
          <div>
            <p class="text-[var(--contentBg)] text-2xl">{{ vocalInfo?.name }}</p>
            <div class="flex text-[var(--icon)] my-2">
              <p>专辑: {{ vocalInfo?.al.name }}</p>
              <p class="mx-10">歌手: {{ singerName }}</p>
              <p>来源: 未知</p>
            </div>
            <ul class="flex w-fit rounded-full bg-[rgba(0,0,0,0.2)] p-1 pr-2">
              <li class="font-bold text-[var(--contentBg)] bg-[rgba(255,255,255,0.2)] rounded-full px-3">歌词</li>
              <li class="mx-3 text-[var(--icon)]">百科</li>
              <li class="text-[var(--icon)]">相似推荐</li>
            </ul>
          </div>
          <!-- 歌词 -->
          <div class=" w-fit h-[calc(100vh-274px)] overflow-auto no-scrollbar mt-3 scroll-smooth" ref="songUlRef">
            <ul class="text-[var(--contentBg)]">
              <li :id="`lyric-${index}`" v-for="(item, index) in lrcInfoList" :key="index"
                class="my-8 py- text-xl transition-all">
                {{ item }}
              </li>
            </ul>
          </div>
        </div>
      </div>
    </div>
    <!-- 分享对话框 -->
    <el-dialog v-model="share" title="分享到" width="300" align-center draggable>
      <ul>
        <li class="py-3 hover:bg-[var(--active)] pl-4 transition-all">
          <i class="iconfont icon-qiepian text-[var(--playBg)] before:text-xl"></i><span
            class="inline-block ml-2">云音乐动态</span>
        </li>
        <li class="py-3 hover:bg-[var(--active)] pl-4 transition-all">
          <i class="iconfont icon-youjian_o text-[var(--playBg)] before:text-xl"></i><span
            class="inline-block ml-2">私信分享</span>
        </li>
        <li class="py-3 hover:bg-[var(--active)] pl-4 transition-all">
          <i class="iconfont icon-weixin text-[var(--playBg)] before:text-xl"></i><span
            class="inline-block ml-2">微信好友</span>
        </li>
        <li class="py-3 hover:bg-[var(--active)] pl-4 transition-all">
          <i class="iconfont icon-QQ text-[var(--playBg)] before:text-xl"></i><span
            class="inline-block ml-2">QQ好友</span>
        </li>
        <li class="py-3 hover:bg-[var(--active)] pl-4 transition-all">
          <i class="iconfont icon-xinlang text-[var(--playBg)] before:text-xl"></i><span
            class="inline-block ml-2">微博</span>
        </li>
        <li @click="copyLink" class="py-3 hover:bg-[var(--active)] pl-4 transition-all mb-3">
          <i class="iconfont icon-lianjie text-[var(--playBg)] before:text-xl"></i><span
            class="inline-block ml-2">复制链接</span>
        </li>
      </ul>
      <Transition name="fade">
        <p v-show="showText"
          class="w-fit p-3 rounded-md bg-[var(--active)] left-1/2 translate-x-[-50%] bottom-[-3rem] absolute">链接复制成功</p>
      </Transition>
    </el-dialog>
  </div>
</template>
<script setup lang='ts'>
import { onMounted, ref, watch, getCurrentInstance, computed, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ArrowDownBold } from '@element-plus/icons-vue'
import login from '@renderer/components/login.vue'
import user from '@renderer/components/userInfo.vue'
import { storeToRefs } from 'pinia'
import { songInfo } from '@renderer/store/modules/eveylSong/type'
import { useStore } from '@renderer/store'
import type { profileType } from "@renderer/store/modules/login/type"
const { recSingList, userSongList } = useStore()
const { userSongList_playlist } = storeToRefs(userSongList)
const userInfo = ref<profileType>(JSON.parse(localStorage.getItem('user') as string))
const { ipcRenderer } = require('electron');
const router = useRouter()
// 指定this
const ctx = getCurrentInstance()
const bus = ctx?.appContext.config.globalProperties.$bus
let isLogin = ref(true)
const playbackRef = ref()
const lrcInfoList = ref<Array<string>>([])
const lrcRef = ref<HTMLDivElement>()
const songUlRef = ref<HTMLDivElement>()
const rotateContentRef = ref<HTMLDivElement>()
const stylusImgRef = ref<HTMLImageElement>()
const vocalInfo = ref<songInfo>()
const isPlay = ref(false)
const showText = ref(false)
const themeValue = ref(false)
const share = ref(false)
const showUserSongList = ref(true)
const isFullScreen = ref(true)
const musicLink = ref('')
const lyricsArr = ref([] as { time: number, text: string }[])
const lastPlayTime = ref(0)
let nowMusicInfo = reactive({} as musicInfoType)
interface Lrc {
  item: songInfo
  lrc_lyricList: Array<string>
}
type musicInfoType = {
  musicUrl: string
  musicInfo: songInfo
  curTime: number
}
onMounted(() => {
  bus.on('login', async () => {
    isLogin.value = false
    await recSingList.getRecomSingList()
    userInfo.value = JSON.parse(localStorage.getItem("user") as string)
    getUserSongList()
  })
  bus.on('loginOut', () => {
    isLogin.value = true
    userSongList_playlist.value = []
  })
  bus.on('openShare', (url: string) => {
    share.value = true
    musicLink.value = url
  })
  getUserSongList()
})
watch(isLogin, () => {
  if (isLogin.value && localStorage.getItem("user") !== null) {
    isLogin.value = false
  }
}, {
  immediate: true
})
const handleClick = (event: Event) => {
  // 获取点击的元素
  const target = event.target as HTMLElement;

  // 检查点击的元素是否为li
  if (target.tagName === 'LI') {
    // 获取所有的li元素
    const items = document.querySelectorAll('.leftMenu');

    // 遍历所有li元素，移除active类名
    items.forEach((item) => {
      item.classList.remove('active');
    });

    // 为被点击的li元素添加active类名
    target.classList.add('active');
  }
}
const goToBolg = () => {
  router.push('/bolg')
}
const goToHome = () => {
  router.push('/')
}
// 得到当前播放的歌曲信息
const getMusicInfo = (item: musicInfoType) => {
  nowMusicInfo.musicInfo = item.musicInfo
  nowMusicInfo.musicUrl = item.musicUrl
}
// 关闭按钮
const closeBtn = () => {
  nowMusicInfo.curTime = lastPlayTime.value
  if (nowMusicInfo.hasOwnProperty("musicInfo")) {
    localStorage.setItem('cacheMusicInfo', JSON.stringify(nowMusicInfo))
  }
  ipcRenderer.send('window-close')
}
// 最小化按钮
const minBtn = () => {
  ipcRenderer.send('window-min')
}
// 最大化按钮
const maxBtn = () => {
  ipcRenderer.send('window-max')
}

// 解析歌词信息
function parseLyrics(line: string) {
  const match = line.match(/\[(\d{2}):(\d{2}\.\d{2,3})\](.*)/);
  if (match) {
    const time = parseInt(match[1]) * 60 + parseFloat(match[2]);
    const text = match[3];
    if (text) {
      lyricsArr.value.push({ time, text });
    }
  }
}
// 设置当前播放的歌词样式
function setLyricStyle(currentTime: number, lyricsArray: { time: number, text: string }[]) {
  let currentLyricIndex = -1;
  for (let i = 0; i < lyricsArray.length; i++) {
    if (currentTime + 0.15 >= lyricsArray[i].time) {
      currentLyricIndex = i;
    } else {
      break;
    }
  }
  if (currentLyricIndex !== -1) {
    // 设置当前歌词样式
    const currentLyric = document.getElementById(`lyric-${currentLyricIndex}`) as HTMLLIElement;
    bus.emit('desktopLyrics', currentLyric.textContent)
    // 将播放过的歌词设置为默认颜色
    for (let i = 0; i < lyricsArray.length; i++) {
      const lyric = document.getElementById(`lyric-${i}`) as HTMLLIElement;
      if (lyric) {
        lyric.style.color = 'var(--contentBg)';
      }
    }
    // 将当前歌词设置为主题色
    currentLyric.style.color = 'var(--playBg)';
    // 设置上一句歌词样式
    if (currentLyricIndex > 0) {
      const prevLyric = document.getElementById(`lyric-${currentLyricIndex - 1}`) as HTMLLIElement;
      prevLyric.style.color = 'var(--contentBg)';
    }
    // 歌词滚动
    if (songUlRef.value) {
      songUlRef.value.scrollTop = currentLyric.offsetTop - songUlRef.value.offsetTop * 2
    }
  }
}
// 歌曲播放时间改变回调
const getPlayTime = (value: number) => {
  lastPlayTime.value = value
  setLyricStyle(value, lyricsArr.value)
}
// 歌词信息
const lrcInfo = (value: Lrc) => {
  value.lrc_lyricList = value.lrc_lyricList.filter(item => item !== '')
  lrcInfoList.value = []
  lyricsArr.value = []
  // 过滤作家信息
  let lrcInfoReg: RegExp = /{.*"t":-?\d+,"c":\[(?:{.*"tx":".*?",?})+\]}/
  let reg = /(\[\d{2}:\d{2}\.\d{2,3}\])/g
  value.lrc_lyricList.forEach((item, index) => {
    parseLyrics(item)
    lrcInfoList.value.push(item.replace(reg, ''))
    if (lrcInfoReg.test(item)) {
      const { t, c } = JSON.parse(item)
      let text = c.map((i: { tx: string }) => i.tx).join('')
      lyricsArr.value.unshift({ time: t / 1000, text })
      let lrcInfo = ""
      c.forEach((i: { tx: string }) => {
        lrcInfo += i.tx
      })
      lrcInfo = lrcInfo.replace(/\//g, " / ")
      lrcInfoList.value[index] = lrcInfo
    }
  })
  lyricsArr.value.sort((a, b) => a.time - b.time)
  lrcInfoList.value = lrcInfoList.value.filter(item => {
    return item !== ''
  })

  lrcInfoList.value.length == 0 ? lrcInfoList.value.unshift('此歌曲为没有填词的纯音乐，请您欣赏') : ''
  vocalInfo.value = value.item
  songUlRef.value!.scrollTop = 0
}
// 全屏显示
const fullScreen = () => {
  ipcRenderer.send('window-full')
  isFullScreen.value = false
}
// 退出全屏
const backFullScreen = () => {
  ipcRenderer.send('window-exit-full')
  isFullScreen.value = true
}
// 缩小详情页
const backToHome = () => {
  playbackRef.value.resetPlayback()
  lrcRef.value!.style.transform = 'translateY(0)'
}
// 展开详情页
const openDetails = () => {
  lrcRef.value!.style.transform = 'translateY(-100%)'
}
// 歌手
const singerName = computed(() => {
  if (vocalInfo.value?.ar.length == 1) {
    return vocalInfo.value?.ar[0].name
  } else if (vocalInfo.value == undefined) {
    return "未知歌手"
  } else {
    return vocalInfo.value?.ar[0].name + ' / ' + vocalInfo.value?.ar[1].name
  }
})
// 旋转动画暂停
const ChangeRotatePause = () => {
  rotateContentRef.value!.style.animationPlayState = 'paused'
  isPlay.value = true
}
// 旋转动画恢复
const ChangeRotateRun = () => {
  rotateContentRef.value!.style.animationPlayState = 'running'
  isPlay.value = false
}
// 获取用户歌单
const getUserSongList = async () => {
  if (userInfo.value !== null && userSongList_playlist.value.length == 0) {
    await userSongList.getUserSongList(userInfo.value.userId)
    showUserSongList.value = true
  }
  else return
}
// 跳转推荐歌单详情页
const goToSongListDetail = (id: number | string) => {
  router.push({ path: '/songListDetail', query: { id: id } })
}
// 复制链接
const copyLink = () => {
  showText.value = true
  setTimeout(() => {
    showText.value = false
  }, 1500)
  navigator.clipboard.writeText("https://gitee.com/fangshengsf")
}
</script>
<style scoped lang="less">
header {
  &>div {
    -webkit-app-region: drag;
    transform: rotate(0deg) translateX();
  }

  * {
    -webkit-app-region: no-drag;
  }
}

.animate-spin {
  animation: spin 50s linear infinite;
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.5s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

.animate_bg {
  background: linear-gradient(125deg, var(--c1), var(--c2), var(--c3), var(--c4), var(--c5));
  background-size: 500%;
  animation: animateBg 30s linear infinite;
}

@keyframes animateBg {
  0% {
    background-position: 0% 50%;
  }

  50% {
    background-position: 100% 50%;
  }

  100% {
    background-position: 0% 50%;
  }
}

:deep(.el-dialog) {
  padding: 0;
  border-radius: 15px;
}

:deep(.el-dialog__header) {
  margin: 1rem 1rem 0;
}

.active {
  background-color: var(--active);
  font-weight: bold;
}
</style>